package com.biomatch.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.biomatch.domain.*;
import com.biomatch.mapper.RoleMapper;
import com.biomatch.mapper.RolePermissionMapper;
import com.biomatch.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public UserInfo getRoleAndPermissionByUserInfo(UserInfo userInfo) {
        //获取用户身份
        Role role = roleMapper.getRoleByUserCode(userInfo.getUsrcod());
        //通过角色获取权限
        List<String> permissions = new ArrayList<>();
        if (role != null) {
            QueryWrapper<RolePermission> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("RoleCode", role.getRoleId());
            List<RolePermission> rolePermissionList = rolePermissionMapper.selectList(queryWrapper);
            for (RolePermission rp : rolePermissionList) {
                permissions.add(rp.getPermissionCode());
            }
        }
        //封装角色、权限
        userInfo.setRole(role);
        userInfo.setPermissions(permissions);
        return userInfo;
    }
}